package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.controller.po.InsertEmpParam;
import com.itheima.tlias84.controller.po.SelectEmpPageParam;
import com.itheima.tlias84.dao.entity.Emp;
import com.itheima.tlias84.service.EmpService;
import com.itheima.tlias84.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    EmpService empService;

    @GetMapping("/list")
    public ResultUtil selectAllEmp() {
        List<Emp> list = empService.selectAll();
        return ResultUtil.success(list);
    }

    @GetMapping
    public ResultUtil selectPage(SelectEmpPageParam param) {
        if (!Objects.isNull(param.getPage()) && !Objects.isNull(param.getPageSize())) {
            return empService.selectPage(param);
        }else {
            return ResultUtil.failure();
        }
    }

    @GetMapping("/{id}")
    public ResultUtil selectById(@PathVariable Integer id) {
        return ResultUtil.success(empService.selectById(id));
    }

    @Log
    @DeleteMapping
    public ResultUtil deleteEmp(@RequestParam("ids") List<Integer> ids) {
        if (!ids.isEmpty()) {
            int i = empService.deleteEmp(ids);
            return ResultUtil.success("成功删除了" + i + "条数据");
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PostMapping
    public ResultUtil insertEmp(@Validated @RequestBody InsertEmpParam param){
        log.info("新增员工参数:{}", param);
        int flag = empService.insertEmp(param);
        if (flag == 1) {
            return ResultUtil.success();
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PutMapping
    public ResultUtil updateEmp(@Validated @RequestBody InsertEmpParam param) {
        int flag = empService.updateEmp(param);
        if (flag == 1) {
            return ResultUtil.success();
        }else {
            return ResultUtil.failure();
        }
    }
}
